import { DownloadOutlined, SettingOutlined } from "@ant-design/icons";
import { BetaSchemaForm } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout"
import ProTable, { ActionType } from "@ant-design/pro-table";
import { useForm, useModal, toWebUrl, useAxiosWebGet, useAxiosWebPost, useCtx, useModalForm, useAxiosGet } from "@sker/sdk";
import { renderAdminPage, useServerData, SkerUploadOne } from "@sker/ui"
import { Button, Card, Modal, Tabs, App } from "antd";
import { useEffect, useRef, useState } from "react";

export const AddonPage: React.FC<{}> = ({ }) => {
    const [serverData] = useServerData();
    const { message } = useCtx()
    const uploadUrl = toWebUrl('imeepos/core/addon/upload')
    const [activeKey, setActiveKey] = useState<string>(`uninstall`)
    const { fetch: fetchLocal } = useAxiosWebGet('imeepos/core/addon/list')
    const { data: addonSetting, fetch: getAddonSetting } = useAxiosWebGet('imeepos/core/addon/setting')
    const { fetch: installAddon } = useAxiosWebPost('imeepos/core/addon/install')
    const { fetch: reinstallAddon } = useAxiosWebPost('imeepos/core/addon/reinstall')
    const { fetch: uninstallAddon } = useAxiosWebPost('imeepos/core/addon/uninstall')
    const { fetch: settingAddon } = useAxiosWebPost('imeepos/core/addon/setting')
    const { fetch: buildAddon } = useAxiosGet('imeepos/core/build')
    const [state, setState] = useState<any>({})
    const { props: installProps, setOpen: setInstallOpen } = useModal('上传应用')
    const actionRef = useRef<ActionType>()
    const app = App.useApp();
    const { props: installForm } = useForm([
        {
            title: '上传zip包',
            renderFormItem(schema, config, form, action) {
                return <SkerUploadOne value={[]} action={uploadUrl} onUpload={(values) => {
                    app?.message?.success(`成功上传${values.title}@${values.version}应用`)
                }} />
            },
        }
    ], async (values) => {
        setInstallOpen(false);
        actionRef.current?.reload();
    })
    const addonLogoUploadUrl = toWebUrl('imeepos/core/addon/uploadLogo')
    const { formProps: settingForm, form, modalProps: settingProps, setOpen: setSettingOpen, record } = useModalForm({
        title: '应用设置',
        onCancel: () => {
            setState({ setting: '' })
        },
        columns: () => {
            return [
                { title: '平台名称', dataIndex: 'title' },
                { dataIndex: 'name', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
                {
                    title: '平台LOGO', dataIndex: 'logo', renderFormItem(schema, config, form, action) {
                        const value = form.getFieldValue('logo')
                        return <SkerUploadOne value={[{ uid: value, naem: value, url: value }]} params={{ name: record?.name }} action={addonLogoUploadUrl} onUpload={(values) => {
                            form.setFieldValue('logo', values)
                        }} />
                    },
                },
                { title: '登录地址', dataIndex: 'login_url' },
            ]
        },
        onFinish: async (values) => {
            await settingAddon({
                name: values.name,
                setting: values
            })
            setState({ setting: '' })
            setSettingOpen(false)
            actionRef.current?.reload();
        }
    })
    useEffect(() => {
        if (!addonSetting) return;
        form.setFieldsValue(addonSetting.data)
    }, [addonSetting])
    return <PageContainer title={serverData?.title || '应用管理'} extra={<Button type={'primary'} icon={<DownloadOutlined />} onClick={e => {
        setInstallOpen(true)
    }}>上传</Button>}>
        <Modal {...installProps}>
            <BetaSchemaForm {...installForm} />
        </Modal>
        <Modal {...settingProps}>
            <BetaSchemaForm {...settingForm} />
        </Modal>
        <Tabs className="bg-white px-24px empty" activeKey={activeKey} onChange={setActiveKey} items={[{
            label: '未安装',
            key: 'uninstall'
        }, {
            label: '已安装',
            key: 'installed'
        }, {
            label: '待更新',
            key: 'upgrade'
        }]}></Tabs>
        <Card className="mt-24px">
            <ProTable
                search={false}
                toolBarRender={false}
                params={{
                    status: activeKey
                }}
                actionRef={actionRef}
                rowKey={record => record.name}
                columns={[
                    { title: '序', dataIndex: 'aid' },
                    { title: '应用名', dataIndex: 'title' },
                    { title: '简介', dataIndex: 'desc' },
                    { title: '应用代号', dataIndex: 'name' },
                    { title: '版本号', dataIndex: 'version' },
                    {
                        title: '操作', align: 'right', render(dom, entity, index, action, schema) {
                            return <>
                                {entity.status === 'upgrade' && <Button type={'primary'} onClick={e => {
                                    app.message.error(`开发小哥正在加班加点开发中，请耐心等待更新！`)
                                }}>更新</Button>}
                                {entity.status === 'uninstall' && <Button type={'primary'} loading={state?.uninstall === entity.name} onClick={async e => {
                                    setState({ uninstall: entity.name })
                                    await installAddon({ name: entity.name })
                                    setState({ uninstall: '' })
                                    actionRef.current?.reload()
                                }}>安装应用</Button>}
                                {entity.status === 'installed' && <Button type={'link'} icon={<SettingOutlined />} loading={state?.setting === entity.name} onClick={async e => {
                                    setState({ setting: entity.name })
                                    await getAddonSetting({ name: entity.name })
                                    setSettingOpen(true, entity)
                                }}>设置</Button>}
                                {entity.status === 'installed' && <Button type={'link'} loading={state?.build === entity.name} onClick={async e => {
                                    setState({ build: entity.name })
                                    await buildAddon({ name: entity.name })
                                    setState({ build: '' })
                                    message.success(`构建成功`)
                                    actionRef.current?.reload()
                                }}>构建</Button>}
                                
                                {entity.status === 'installed' && <Button type={'link'} loading={state?.reinstall === entity.name} onClick={async e => {
                                    setState({ reinstall: entity.name })
                                    await reinstallAddon({ name: entity.name })
                                    setState({ reinstall: '' })
                                    actionRef.current?.reload()
                                }}>重装</Button>}

                                {entity.status === 'installed' && <Button danger loading={state?.installed === entity.name} type={'link'} onClick={async e => {
                                    setState({ installed: entity.name })
                                    await uninstallAddon({ addon: entity.name })
                                    setState({ installed: '' })
                                    actionRef.current?.reload()
                                }}>卸载</Button>}
                            </>
                        },
                    }
                ]}
                request={async (params) => {
                    return fetchLocal(params)
                }} />
        </Card>

    </PageContainer>
}

renderAdminPage(AddonPage, 'imeepos/core/web/addon')